package com.smmisia.article.config;

import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/video/{roomId}")
@Slf4j
public class VideoWebSocketServer {
    
    private static final Map<String, Session> rooms = new ConcurrentHashMap<>();
    
    @OnOpen
    public void onOpen(Session session, @PathParam("roomId") String roomId) {
        log.info("新的视频连接加入房间: {}", roomId);
        rooms.put(roomId, session);
    }
    
    @OnMessage
    public void onMessage(String message, Session session, @PathParam("roomId") String roomId) {
        log.info("收到来自房间 {} 的消息: {}", roomId, message);
        rooms.forEach((key, otherSession) -> {
            if (!key.equals(roomId) && otherSession.isOpen()) {
                try {
                    otherSession.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    log.error("发送消息失败", e);
                }
            }
        });
    }
    
    @OnClose
    public void onClose(Session session, @PathParam("roomId") String roomId) {
        log.info("房间 {} 的连接关闭", roomId);
        rooms.remove(roomId);
    }
    
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("WebSocket错误", error);
    }
}